﻿using System.Collections;
using BaseData.CommonLib.Models;
using BaseData.RazorLib.Services;
using Microsoft.AspNetCore.Components;

namespace BaseData.RazorLib.Pages;

public partial class MaterialEdit
{
    private MaterialEditRequestDto _editRequestDto = new();


    private IList<CalculateUnitInfoResponseDto> _units = new List<CalculateUnitInfoResponseDto>();
    private List<MaterialCategoryTreeResponseDto> TreeData = new();

    [CascadingParameter] public MaterialIndex? MaterialIndex { get; set; }

    [Inject] public ICalculateUnitService CalculateUnitService { get; set; }

    [Inject] public IMaterialCategoryService MaterialCategoryService { get; set; }

    [Inject] public IMaterialService MaterialService { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        var key = MaterialIndex?.GetKey();
        if (key > 0)
        {
            var result = await MaterialService.GetMaterial(key);
            if (result.Succeeded)
            {
                _editRequestDto.Code = result.Data.Code;
                _editRequestDto.Name = result.Data.Name;
                _editRequestDto.Specification = result.Data.Specification;
                _editRequestDto.Unit = result.Data.Unit;
                _editRequestDto.MaterialType = result.Data.MaterialType;
            }
        }

        await base.OnParametersSetAsync();
    }

    object GetItemFromTreeHandler(IEnumerable data, object value)
    {
        MaterialCategoryTreeResponseDto? materialCategoryTreeResponseDto = null;
        var materialCategoryTreeResponseDtos = (IList<MaterialCategoryTreeResponseDto>)data;
        var currentValue = (int)value;
        if (materialCategoryTreeResponseDtos.Count > 0 && currentValue > 0)
        {
            materialCategoryTreeResponseDto = GetChildSelectedItem(materialCategoryTreeResponseDtos, currentValue);
        }

        return materialCategoryTreeResponseDto!;
    }

    private MaterialCategoryTreeResponseDto? GetChildSelectedItem(
        IList<MaterialCategoryTreeResponseDto> treeResponseDtos, int value)
    {
        MaterialCategoryTreeResponseDto? item = null;
        foreach (var childItem in treeResponseDtos)
        {
            if (childItem.Children != null)
            {
               return GetChildSelectedItem(childItem.Children, value);
            }

            if (childItem.Key == value)
            {
                item = childItem;
                break;
            }
        }

        return item;
    }
}